package cn.suchan.sharedelectrombile.controller;

import cn.suchan.sharedelectrombile.entity.Role;
import cn.suchan.sharedelectrombile.entity.User;
import cn.suchan.sharedelectrombile.repository.RoleRepositroy;
import cn.suchan.sharedelectrombile.response.Response;
import cn.suchan.sharedelectrombile.response.ResponseCode;
import cn.suchan.sharedelectrombile.service.RoleService;
import cn.suchan.sharedelectrombile.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*@Controller*/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AppController appController;

    /**
     * 用户登录
     * 查询该用户属于什么角色以及拥有什么权限
      * @param user
     * @return
     */
    @PostMapping(value = "/login")
    public List<Response> userTest(@RequestBody @Valid User user, BindingResult bindingResult){
        List<Response> responseList = new ArrayList<>();
        System.out.println("user==>" + user.toString());
        if (bindingResult.hasErrors()){
            responseList = appController.validResult(bindingResult);
        }else{
            List<Integer> ridList = userService.getRidByUnameAndUpassword(user);
            Set<Integer> allRsidSet = new HashSet<>();
            /*Set<Role> roles = new HashSet<>();*/
            if (ridList.size() > 0){
                ridList.forEach(rid->{
                    System.out.println("rid==>" + rid);
                    List<Integer> rsidList = roleService.findByRid(rid);
                    rsidList.forEach(rsid->{
                        allRsidSet.add(rsid);
                    });
                   /* roles.add(roleService.getOne(rid));*/
                });
                /*System.out.println("roles==>" + roles);*/
                /*user.setRoleSet(roles);*/

                /*ridList.forEach(System.out::println);*/
                Response rs = new Response();
                rs.setCode("Success");
                rs.setMsg("请求成功");
                rs.setData(allRsidSet);
                responseList.add(rs);
                /*return new Response(ResponseCode.SUCCESS,user);*/
            }
        }
        /*System.out.println("response==>" + response.toString());*/
        /*return new Response(ResponseCode.FAIL,user);*/
        /*return response;*/
        return responseList;
    }
}
